package token

import (
	"fmt"
	"github.com/dgrijalva/jwt-go"
)

func CreateToken(key string, m map[string]interface{}) string {

	claims := make(jwt.MapClaims)
	for index, val := range m {
		claims[index] = val
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, _ := token.SignedString([]byte(key))
	return tokenString
}

func Parse(tokenString string, key string) (interface{}, bool) {

	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		return []byte(key), nil
	})
	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		return claims, true
	} else {
		fmt.Println(err)
		return "", false
	}
}

func IsTokenExpire(token interface{}, field string, endtm int64, difftm int64) bool {

	v := int64(token.(jwt.MapClaims)[field].(float64))

	tm := endtm - v
	if tm > 0 && tm >= difftm {
		return true
	} else {
		return false
	}

	return false
}

func GetsTokenfield(token interface{}, field string) interface{} {
	return token.(jwt.MapClaims)[field]
}
